package com.ruoyi.web.controller.system;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysEnterprise;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.SysUserEnterprise;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysEnterpriseService;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserEnterpriseService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController {
    private SysLoginService loginService;

    private ISysMenuService menuService;

    private SysPermissionService permissionService;

    private TokenService tokenService;

    private ISysEnterpriseService sysEnterpriseService;

    private ISysUserEnterpriseService sysUserEnterpriseService;

    private SysUserServiceImpl sysUserService;

    @Autowired
    public SysLoginController(SysLoginService loginService, ISysMenuService menuService, SysPermissionService permissionService, TokenService tokenService,
                              ISysEnterpriseService sysEnterpriseService, ISysUserEnterpriseService sysUserEnterpriseService, SysUserServiceImpl sysUserService) {
        this.loginService = loginService;
        this.menuService = menuService;
        this.permissionService = permissionService;
        this.tokenService = tokenService;
        this.sysEnterpriseService = sysEnterpriseService;
        this.sysUserEnterpriseService = sysUserEnterpriseService;
        this.sysUserService = sysUserService;
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 企业微信登录
     */
    @GetMapping(value = "/enterpriseLogin")
    @ResponseBody
    @Transactional
    public AjaxResult enterpriseLogin(@RequestParam("code") String code, @RequestParam("corpid") String corpid) {
        AjaxResult ajax = AjaxResult.success();
        try {
            // 查找是否还存在这个企业
            SysEnterprise enterprise = sysEnterpriseService.selectSysEnterpriseByCorpid(corpid);
            if (Objects.isNull(enterprise)) {
                return AjaxResult.error("该企业不存在");
            }
            String accessToken = loginService.getEnterpriseAccessToken(corpid, enterprise.getCorpsecret());
            Map<String, Object> param = new HashMap<>(2);
            param.put("access_token", accessToken);
            param.put("code", code);
            String result = HttpUtil.get("https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo", param, 7200);
            JSONObject jsonObject = JSON.parseObject(result);
            Integer errcode = (Integer) jsonObject.get("errcode");
            if (errcode == 0) {
                String userId = (String) jsonObject.get("userid");
                QueryWrapper<SysUserEnterprise> userEnterpriseQueryWrapper = new QueryWrapper<>();
                userEnterpriseQueryWrapper
                        .eq("enterprise_user_id", userId)
                        .eq("enterprise_corp_id", corpid);
                SysUserEnterprise userEnterprise = this.sysUserEnterpriseService.getOne(userEnterpriseQueryWrapper);
                if (Objects.nonNull(userEnterprise)) {
                    // 先查找用戶数据
                    SysUser user = this.sysUserService.selectUserById(userEnterprise.getUserId());
                    // 生成令牌
                    String token = loginService.login(user, userEnterprise, userId, enterprise.getCorpsecret());
                    ajax.put(Constants.TOKEN, token);
                    return ajax;
                }
            }
            // 请求重定向
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
        return AjaxResult.error("登录失败");
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions)) {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
